package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var (
	db *sql.DB
)


type WebsiteLink struct {
	ID int `json:"id"`
	Name string `json:"name"`
	Slink string `json:"slink"`
	CategoryId int `json:"category_id"`

}

type WebsiteCategory struct {
	ID int `json:"id"`
	Name string `json:"name"`
}

func initDB() (err error)  {
	dsn := "root:root@(127.0.0.1)/site?charset=utf8mb4&parseTime=True&loc=Local"
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	err = db.Ping()
	if err != nil {
		return err
	}
	return
}




func main(){
	err := initDB()
	if err != nil {
		fmt.Println(err)
	}

siteLink := make(map[string]interface{}, 10)
links := []string{}

	categoryIdSql := "select id,name from website_category;"

	c, err := db.Query(categoryIdSql)
	if err != nil {
		fmt.Println(err)
		return
	}

	for c.Next() {
		var category WebsiteCategory

		c.Scan(&category.ID, &category.Name)
		fmt.Printf("%d\n", category.ID)

		sqlStr := "select website_link.id, website_link.name, website_link.slink, website_category.name from website_link,website_category where website_link.category_id = ?;"
		s, err := db.Query(sqlStr, category.ID)
		if err != nil {
			fmt.Print(err)
			return
		}
		//defer  s.Close()

		for s.Next() {
			var l WebsiteLink
			var cc WebsiteCategory
			err := s.Scan(&l.ID, &l.Name, &l.Slink, &cc.Name )
			if err != nil {
				fmt.Println("1---",err)
				return
			}
			fmt.Printf("linkID: %d linkName: %s,link: %s categoryName: %s\n", l.ID, l.Name, l.Slink, cc.Name)

			m := make(map[string]interface{}, 10)
			m["id"] = l.ID
			m["name"] = l.Name
			m["link"] = l.Slink
			ret, err := json.Marshal(m)
			if err != nil {
				fmt.Println(err)
				return
			}
			fmt.Println(string(ret))
			links = append(links, string(ret))
		}
	siteLink["name"] = category.Name
	siteLink["links"] = links
	}

	defer c.Close()

siteJson, err := json.Marshal(siteLink)
if err != nil {
	fmt.Println(err)
}
fmt.Println(string(siteJson))
}